package com.example.ddcoursequery;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QueryCourseByTeacher extends Activity {
    private Spinner semesterspinner;
    private String semesterValue;

    private AutoCompleteTextView autoCompleteTextView;
    private String[] teacherArray;

    private String id;
    private String name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_querycoursebyteacher);

        Intent intent = getIntent();
        if(intent != null ){
            String error = intent.getStringExtra("error");
            Log.i("lyj","Jump From QueryCourseByImg error = "+error);
            if(!TextUtils.isEmpty(error)){
                Toast.makeText(QueryCourseByTeacher.this,error,Toast.LENGTH_LONG).show();
            }

        }

        //下拉列表
        semesterspinner = (Spinner) findViewById(R.id.semesters);
        initSemesterSpinner();
        getSemesterValue();

        //自动填充
        autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.teacherText);
        initAutoComplete();
        turnToQueryCourse();
    }

    private void initAutoComplete() {
        new AsyncTask<String, String, String>() {

            @Override
            protected String doInBackground(String... strings) {
                try {
                    if(CacheTeacher.teacherList != null && CacheTeacher.teacherList.size() != 0){
                        teacherArray = new String[CacheTeacher.teacherList.size()];
                        for(int i = 0;i < teacherArray.length;i++){
                            teacherArray[i] = CacheTeacher.teacherList.get(i).getTeacher_id() + " " +CacheTeacher.teacherList.get(i).getTeacher_name();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                ArrayAdapter arrayAdapter = new ArrayAdapter(QueryCourseByTeacher.this, android.R.layout.simple_list_item_1, teacherArray);
                autoCompleteTextView.setAdapter(arrayAdapter);
            }
        }.execute();
    }

    /**
     * 点击老师时，跳转到该老师的课表查询界面
     * <p>
     * 1.如果该老师的课表在缓存中，则直接跳转到老师课表的显示界面
     * 2.如果该老师的课表在数据库中，则直接跳转到老师课表的显示界面 -- 实现部分
     * 3.如果老师的课表也不在数据库中，则请求Server端发送数据
     */
    private void turnToQueryCourse() {
        autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //Log.i("lyj", "adapterView.count=" + adapterView.getCount() + ",i=" + i);

                //获取选中的老师数据
                String appTeacherStr = (String) adapterView.getAdapter().getItem(i);
                String[] tmp = appTeacherStr.split(" ");
                id = tmp[0];
                name = tmp[1];

                Log.i("lyj", "request parameters id:" + id + "," + "semester:" + semesterValue);

                //2.去Server找课程
                getTeacherCourse(id, semesterValue);
            }
        });
    }


    private void turnToShowCourse() {
        Intent intent = new Intent(QueryCourseByTeacher.this, ShowCourseActivity.class);
        startActivity(intent);
    }

    private void getTeacherCourse(final String id, final String semesterValue) {
        new Thread() {
            @Override
            public void run() {
                HttpData httpData = new HttpData();
                int i = httpData.getCourseList(id, semesterValue);
                if(i == 0){
                    //在显示页面添加以老师名为标题
                    CacheTeacher.titleList.add(0,name);
                    turnToShowCourse();
                }else if(i == -1){
                    turnToShowImg();
                }

            }
        }.start();
    }

    private void turnToShowImg() {
        Intent intent = new Intent(QueryCourseByTeacher.this,QueryCourseByImg.class);
        intent.putExtra("id",id);
        intent.putExtra("name",name);
        intent.putExtra("semester",semesterValue);
        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_querycoursebyteacher, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    //加载下拉列表的数据供用户选择
    private void initSemesterSpinner() {
        String[] tmpsem = getResources().getStringArray(R.array.semestersText);
        ArrayAdapter<String> tmpadapter = new ArrayAdapter<String>(QueryCourseByTeacher.this, android.R.layout.simple_list_item_1, tmpsem);
        semesterspinner.setAdapter(tmpadapter);
    }

    //根据用户选择的学期获取相应的请求字段(Sel_XNXQ)的值
    private void getSemesterValue() {
        semesterspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                semesterValue = Resources.semestersIndex[i];
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }
}
